/* eslint-disable no-undef */
// import { getFile, GET_FILE_URL } from '@/api/file';
// import getConfig from '@/server/getConfig';
// import axios from 'axios';
// import { getFileList, uploadFileMulti } from '@/api/formview';
import { showMessage } from './utils';
// todo 请求文件列表
/*
  data: {
    type: string;
    appId: string;
  }
*/

const conversionBase64 = (blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise(resolve => {
        reader.onload = ({ target: { result } }) => {
            resolve(result);
        };
    });
};

// const saveFileToLocal = (blob, fileName) => {
//   const a = document.createElement('a');
//   const url = window.URL.createObjectURL(blob);
//   const filename = fileName;
//   a.href = url;
//   a.download = filename;
//   a.click();
//   window.URL.revokeObjectURL(url);
//   a.remove();
// };

// todo 下载文件
/*
  data: {
    id: string
    fileName: string
    originName: string
  }

  type: string // pic | file ;   //type === pic 返回base64 否则直接下载打开
*/
// const downFile = async(data, type) => {
//   const { data: blob } = await getFile({
//     id: data.id,
//     fileName: data.saveName
//   });
//   if (type === 'pic') {
//     return await conversionBase64(blob);
//   } else {
//     saveFileToLocal(blob, data.saveName);
//   }
// };

// const fileView = async function fileView(id) {
//   const { data: { ApiUrl }} = await getConfig();
//   const fileViewUrl = `${
//     ApiUrl
//   }onlinePreview?fileId=${id}`;

//   window.open(fileViewUrl);
// };

// const downFileServer = url => {
//   return axios.get(url, {
//     responseType: 'blob'
//   });
// };

const dataURLtoFile = function(dataUrl, filename) {
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
};

// const getListFiles = function(data, headers = {}) {
//   return getFileList(data, headers);
// };

// const upFileMulti = function(data) {
//   return uploadFileMulti(data);
// };

// 选择图片
const chooseImgs = function() {
    return new Promise((r, j) => {
        uni.chooseImage({
            count: 9,
            success: (res) => {
                r({
                    paths: res.tempFilePaths,
                    files: res.tempFiles
                });
            },

            fail: () => {
                j('调用图片失败');
            }
        });
    });
};

// 选择附件
const chooseFile = function() {
    return new Promise((r, j) => {
        uni.chooseImage({
            count: 1,
            success: (res) => {
                r({
                    paths: res.tempFilePaths,
                    files: res.tempFiles
                });
            },

            fail: () => {
                j('上传附件失败');
            }
        });
    });
};

// h5
const getH5Base64ImageByUrl = (url) => {
    const img = new Image()
    //解决跨域问题
    img.setAttribute("crossOrigin", 'anonymous');
    //如果需要兼容ios，这两个顺序一定不能换，先设置crossOrigin后设置src
    img.src = url;
    return new Promise((resolve, reject) => {
        img.onload = () => {
            const canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            resolve({
                success: true,
                //canvas.toDataURL的方法将图片的绝对路径转换为base64编码
                base64: canvas.toDataURL().split(',')[1]
            })
        }
        img.onerror = () => {
            reject({ success: false })
        }
    })
}

const getWeChatBase64ImageByUrl = function(url) {
    return new Promise(async (r, j) => {
        let isErr = false
        // 确认是本地是还是网络的url
        if (url.startsWith('http')) {
            url = await wxDownFileToLocal(url).catch(() => {
                isErr = true
            })
        }

        if (isErr) {
            j('下载图片到本地失败');
            return
        }

        wx.getFileSystemManager().readFile({
            filePath: url, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: ({ data }) => {
                r({
                    success: true,
                    base64: data
                    // base64: 'data:image/jpg;base64,' + data
                })
            },
            fail: (evt) => {
                j({
                    success: false,
                    evt
                })
            }
        });

    })
}

const wxDownFileToLocal = function(url) {
    return new Promise((resolve, reject) => {
        wx.downloadFile({
            url,
            success(e) {
                const { tempFilePath } = e;
                resolve(tempFilePath)
            },
            fail(e) {
                reject(e);
            }
        })
    })
}



const getAliPayBase64ImageByUrl = function(imagePath, self) {
    // 支付宝需要手动添加 
    /* 
    imgWidth: 0, imgHeight: 0
    <canvas
      v-show="false"
      :width="imgWidth"
      :height="imgHeight"
      style="opacity: 0; position: absolute;pointer-events: none;"
      id="canvasForBase64"
    />
    */

    return new Promise((resolve, reject) => {
        my.getImageInfo({
            src: imagePath,
            success: async (res) => {
                const { width, height } = res;
                self.imgWidth = width;
                self.imgHeight = height;
                let canvas = my.createCanvasContext("canvasForBase64");
                canvas.drawImage(imagePath, 0, 0, width, height); // 1. 绘制图片至canvas
                // 绘制完成后执行回调
                canvas.draw(false, async () => {
                    let base64 = await canvas.toDataURL({
                        width,
                        height,
                        quality: 1,
                    });
                    resolve({
                        success: true,
                        base64
                    })

                    // base64 = base64.replace("data:image/png;base64,", "");
                    // await this.uploadImageRequest(base64);
                });
            },
        });
    })
}



const getBase64ImageByUrl = function(url, self) {
    // #ifdef MP-WEIXIN
    return getWeChatBase64ImageByUrl(url)
    // #endif

    // #ifdef MP-ALIPAY
    return getAliPayBase64ImageByUrl(url, self);

    // #endif

    // #ifdef H5
    return getH5Base64ImageByUrl(url);
    // #endif
}

// :TODO: 下载网络上的图片到相册
const downFileForMini = function(url) {
    return new Promise((resolve, reject) => {
        try {
            // #ifdef MP-WEIXIN
            wxDownFileConfirm().then(wxDownFile(url));
            // #endif

            // #ifdef MP-ALIPAY
            alipayDownFileConfirm().then(alipayDownFile(url));
            // #endif


            resolve();
        } catch (error) {
            reject(error);
        }
    })
}

// 确认微信保存图片授权
const wxDownFileConfirm = function() {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: (res) => {
                // 未授权相册权限
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    // 打开授权面板
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success: (res) => {
                            console.log('save photo:', res)
                            resolve()
                        },
                        fail: err => {
                            if (err.errMsg.includes('authorize:fail')) {
                                // 重新打开相册权限
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            // 获取权限成功，给出再次点击图片保存到相册的提示
                                            resolve()
                                        } else {
                                            // 获取权限失败，给出不给权限就无法正常使用的提示
                                            showMessage('授权失败，无法保存图片')
                                            reject();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {
                    resolve();
                }
            }
        })
    })
}

// 确认支付宝保存图片授权
const alipayDownFileConfirm = function() {
    return new Promise((resolve, reject) => {
        my.getSetting({
            success:(res)=>{
              // 此处需要判断是否为false，因为初次进来未授权res.authSetting里不会存在writePhotosAlbum字段，这样会导致直接打开设置的页面，但是因为并未受过权，设置页面不会有相册打开按钮，逻辑就走不通了。
              if (res.authSetting['writePhotosAlbum'] === false){
                // 重新打开相册权限
                my.openSetting({
                  success(settingdata) {
                    console.log('again open===>', settingdata)
                    if (settingdata.authSetting['writePhotosAlbum']) {
                      // 获取权限成功，给出再次点击图片保存到相册的提示
                      resolve()
                    }else {
                      // 获取权限失败，给出不给权限就无法正常使用的提示
                      showMessage('授权失败，无法保存图片')
                      reject('授权失败，无法保存图片')
                    }
                  }
                })
              } else {
                resolve()
              }
            }
          })
    })
}

// 支付宝下载网络文件
const alipayInternetUrlToLocal = function(url) {
    return new Promise((resolve, reject) => {
        my.downloadFile({
          url,
          success({ apFilePath }) {
            resolve(apFilePath)
          },
          fail(res) {
            reject(res)
          },
        });
    })
}

const alipayDownFile = function(url) {
    return new Promise(async (success, fail) => {
        try {
            const filePath = await alipayInternetUrlToLocal(url);
            console.log('转化成功', filePath);
            my.saveImageToPhotosAlbum({
                filePath,
                success: (e) => {
                    showMessage('已保存到相册')
                    success(e);
                },
                fail
            });

        } catch (error) {
            fail(error)
        }
    })
}

const wxDownFile = function(url) {
    return new Promise((resolve, reject) => {
        wxDownFileToLocal(url).then(localUrl => {
            wxSave(localUrl).then(resolve).catch(reject)
        }).catch(reject)
    })
}

const wxSave = function(url) {
    return new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
            filePath: url,
            success: (res) => {
                showMessage('图片保存成功')
                resolve()
            },
            fail: (res) => {
                showMessage('图片保存失败')
                reject();
            }
        })
    })
}

const getWxUrlByBase64 = function(base64) {
    return new Promise((resolve, reject) => {
        const fs = wx.getFileSystemManager();
        const times = new Date().getTime();
        const codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';

        fs.writeFile({
            filePath: codeimg,
            data: base64,
            encoding: 'base64',
            success: (res) => {
                //写入成功了的话，新的图片路径就能用了
                console.log(res)
                resolve(codeimg);
            },
            fail(e) {
                reject(e);
            }
        });
    })
}

const getAlipayUrlByBase64 = function(base64) {
    return new Promise((resolve, reject) => {
        const fs = my.getFileSystemManager();
        const times = new Date().getTime();
        const codeimg = my.env.USER_DATA_PATH + '/' + times + '.png';
        const datas = base64.split(',')
        fs.writeFile({
            data: datas[1] || datas[0],
            filePath: codeimg,
            encoding: 'base64',
            success: () => {
                resolve(codeimg)
            },
            fail: (e) => {
                reject(e)
            },
            complete(e) {
                console.log(e, 'zs结果');
            }
          })
    })
}

// :TODO: 微信下载base64 png图片到相册 调用这个
const wxDownFileBase64 = function(base64) {
    return new Promise(async (resolve, reject) => {
        try {
            await wxDownFileConfirm()
            getWxUrlByBase64(base64).then(localUrl => {
                wxSave(localUrl).then(resolve).catch(reject)
            }).catch(reject)
        } catch (error) {
            reject(error)
        }
    })
}

const alipayDownFileBase64 = function(base64) {
    return new Promise(async (resolve, reject) => {
        try {
            await alipayDownFileConfirm();
            const filePath = await getAlipayUrlByBase64(base64);
            console.log('生成本地文件成功', filePath);

            uni.saveImageToPhotosAlbum({
                filePath,
                success: (e) => {
                    showMessage('保存成功')
                    console.log('2333', e);
                },
                fail: reject,
                complete: (e) => {
                    console.log('查询结果', e);
                }
            })
            // my.saveImageToPhotosAlbum({
            //     filePath,
            //     success: resolve,
            //     fail: reject,
            //     complete(e) {
            //         console.log({
            //             result: e
            //         });
            //     }
            // });
        } catch (error) {
            reject(error)
        }
    })
}


export {
    // downFile,
    // fileView,
    // downFileServer,
    dataURLtoFile,
    conversionBase64,
    // getListFiles,
    // upFileMulti,
    chooseImgs,
    chooseFile,
    getBase64ImageByUrl,
    downFileForMini,
    getWxUrlByBase64,
    wxSave,
    wxDownFileBase64,
    getAlipayUrlByBase64,
    alipayDownFileBase64
    // GET_FILE_URL
};